package org.jeecg.modules.gift.controller;

import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.shiro.SecurityUtils;
import org.jeecg.boot.starter.lock.annotation.JRepeat;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.gift.entity.*;
import org.jeecg.modules.gift.service.IGiftActivityService;
import org.jeecg.modules.gift.service.IGiftActivityUserService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.gift.service.IGiftMachineService;
import org.jeecg.modules.gift.utils.AESUtils;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

/**
 * @Description: 活动用户
 * @Author: jeecg-boot
 * @Date: 2024-07-12
 * @Version: V1.0
 */
@Api(tags = "活动用户")
@RestController
@RequestMapping("/gift/giftActivityUser")
@Slf4j
public class GiftActivityUserController extends JeecgController<GiftActivityUser, IGiftActivityUserService> {
    @Autowired
    private IGiftActivityUserService giftActivityUserService;
    @Autowired
    private IGiftActivityService giftActivityService;

    @Autowired
    private IGiftMachineService giftMachineService;


    @ApiOperation(value = "参加活动", notes = "参加活动")
    @PostMapping(value = "/join")
    public Result<String> joinActivity(@RequestBody GiftJoinActivity joinActivity) {

        // 构建
        SymmetricCrypto symmetricCrypto = new SymmetricCrypto(SymmetricAlgorithm.AES, AESUtils.fixedKey);
        String deviceStr = symmetricCrypto.decryptStr(joinActivity.getCode());
        JSONObject jsonObject = null;
        try {
            jsonObject = JSON.parseObject(deviceStr);
        } catch (Exception e) {
            return Result.error("解密失败");
        }
        if (!jsonObject.containsKey("deviceId")) {
            return Result.error("二维码错误");
        }
        if (!jsonObject.containsKey("timestamp")) {
            return Result.error("二维码错误");
        }

        String deviceId = jsonObject.getString("deviceId");
        Long timestamp = jsonObject.getLong("timestamp");
        if (System.currentTimeMillis() - timestamp > 2 * 60 * 1000) {
            return Result.error("二维码已过期");
        }

        LambdaQueryWrapper<GiftMachine> devWrapper = new LambdaQueryWrapper<>();
        devWrapper.eq(GiftMachine::getMachineCode, deviceId);
        GiftMachine machine = giftMachineService.getOne(devWrapper,false);
        if (machine == null)
            return Result.error("机器不存在");

        GiftActivity activity = giftActivityService.getById(joinActivity.getActivityId());
        if (activity == null)
            return Result.error("活动不存在");

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userId = sysUser.getId();

        LambdaQueryWrapper<GiftActivityUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GiftActivityUser::getUserId, userId);
        queryWrapper.in(GiftActivityUser::getJoinStatus, Arrays.asList("1", "2", "3"));

        if (giftActivityUserService.count(queryWrapper) > 0)
            return Result.error("同一个用户只能同时参加一个活动");

        if (joinActivity(userId, joinActivity.getActivityId()) == 1) {
            return Result.error("活动已参加，请勿重复参加");
        }

        return Result.OK("参与成功");
    }

    /**
     * 分布式锁防重复提交
     *
     * @param userId
     * @param activityId
     * @return
     */
    @JRepeat(lockKey = "#userId", lockTime = 5)
    public int joinActivity(String userId, String activityId) {
        LambdaQueryWrapper<GiftActivityUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GiftActivityUser::getUserId, userId);
        queryWrapper.eq(GiftActivityUser::getActivityId, activityId);

        if (giftActivityUserService.count(queryWrapper) > 0)
            return 1;

        GiftActivityUser giftActivityUser = new GiftActivityUser();
        giftActivityUser.setActivityId(activityId);
        giftActivityUser.setUserId(userId);
        giftActivityUser.setJoinStatus("0");
        giftActivityUserService.save(giftActivityUser);
        return 0;
    }


    /**
     * 分页列表查询
     *
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "我参加的活动", notes = "我参加的活动")
    @GetMapping(value = "/mine/list")
    public Result<IPage<GiftActivity>> queryPageList(
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            HttpServletRequest req) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userId = sysUser.getId();
        Page<GiftActivity> page = new Page<GiftActivity>(pageNo, pageSize);
        IPage<GiftActivity> pageList = giftActivityUserService.selectPageUserActivityList(page, userId);
        return Result.OK(pageList);
    }

    /**
     * 分页列表查询
     *
     * @param giftActivityUser
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "活动用户-分页列表查询")
    @ApiOperation(value = "活动用户-分页列表查询", notes = "活动用户-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<GiftActivityUser>> queryPageList(GiftActivityUser giftActivityUser,
                                                         @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                         @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                         HttpServletRequest req) {
        QueryWrapper<GiftActivityUser> queryWrapper = QueryGenerator.initQueryWrapper(giftActivityUser, req.getParameterMap());
        Page<GiftActivityUser> page = new Page<GiftActivityUser>(pageNo, pageSize);
        IPage<GiftActivityUser> pageList = giftActivityUserService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param giftActivityUser
     * @return
     */
    @AutoLog(value = "活动用户-添加")
    @ApiOperation(value = "活动用户-添加", notes = "活动用户-添加")
    @RequiresPermissions("gift:gift_activity_user:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody GiftActivityUser giftActivityUser) {
        giftActivityUserService.save(giftActivityUser);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param giftActivityUser
     * @return
     */
    @AutoLog(value = "活动用户-编辑")
    @ApiOperation(value = "活动用户-编辑", notes = "活动用户-编辑")
    @RequiresPermissions("gift:gift_activity_user:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody GiftActivityUser giftActivityUser) {
        giftActivityUserService.updateById(giftActivityUser);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "活动用户-通过id删除")
    @ApiOperation(value = "活动用户-通过id删除", notes = "活动用户-通过id删除")
    @RequiresPermissions("gift:gift_activity_user:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        giftActivityUserService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "活动用户-批量删除")
    @ApiOperation(value = "活动用户-批量删除", notes = "活动用户-批量删除")
    @RequiresPermissions("gift:gift_activity_user:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.giftActivityUserService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "活动用户-通过id查询")
    @ApiOperation(value = "活动用户-通过id查询", notes = "活动用户-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<GiftActivityUser> queryById(@RequestParam(name = "id", required = true) String id) {
        GiftActivityUser giftActivityUser = giftActivityUserService.getById(id);
        if (giftActivityUser == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(giftActivityUser);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param giftActivityUser
     */
    @RequiresPermissions("gift:gift_activity_user:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, GiftActivityUser giftActivityUser) {
        return super.exportXls(request, giftActivityUser, GiftActivityUser.class, "活动用户");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequiresPermissions("gift:gift_activity_user:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, GiftActivityUser.class);
    }

}
